
(function () {
    //graph初始化
    var graph = new joint.dia.Graph;

    //自定义link
    joint.shapes.standard.Link.define('app.Link', {
        smooth : true,
        labels: [],
        attrs: {
            line: {
                stroke: '#20C1DD',
                strokeDasharray: '0',
                strokeWidth: 2,
                fill: 'none',
                sourceMarker: {
                    type: 'path',
                    d: 'M 0 0 0 0',
                    stroke: 'none'
                },
                targetMarker: {
                    type: 'path',
                    d: 'M 0 -5 -10 0 0 5 z',
                    stroke: 'none'
                }
            }
        }
    }, {

        getMarkerWidth: function(type) {
            var d = (type === 'source') ? this.attr('line/sourceMarker/d') : this.attr('line/targetMarker/d');
            return this.getDataWidth(d);
        },

        getDataWidth: _.memoize(function(d) {
            return (new g.Path(d)).bbox().width;
        })

    }, {

        connectionPoint: function(line, view, magnet, opt, type, linkView) {
            var markerWidth = linkView.model.getMarkerWidth(type);
            opt = { offset: markerWidth, stroke: true };
            // connection point for UML shapes lies on the root group containg all the shapes components
            if (view.model.get('type').indexOf('uml') === 0) opt.selector = 'root';
            return joint.connectionPoints.boundary.call(this, line, view, magnet, opt, type, linkView);
        }
    });
    //paper初始化
    var paper = new joint.dia.Paper({
        width: 2000,
        height: 1500,
        model: graph,
        gridSize: 1,
        snapLinks: true,
        linkPinning: false,
        defaultLink: new joint.shapes.app.Link({
            // router: { name: 'manhattan' },
            // connector: { name: 'rounded' },
            smooth : true,
            attrs: {
                '.connection': {
                    stroke: '#20C1DD',
                    'stroke-width': 2,
                    //    'stroke-dasharray': '5 2',
                    pointerEvents: 'none',
                },
                '.marker-target': {
                    fill: '#20C1DD',
                    stroke: '#fff',
                    d: 'M 10 0 L 0 5 L 10 10 z'
                }
            },
        }),
        defaultConnectionPoint: joint.shapes.app.Link.connectionPoint
    });
    //paper背景
    var bgimage = ''
    paper.drawBackground({
        image : bgimage
    });

    //控制纸张
    var paperScroller = new joint.ui.PaperScroller({
        paper: paper,
        autoResizePaper: true,
        padding: 50,
        cursor: 'grab'
    });
    // 移动纸张
    paper.on('blank:pointerdown', paperScroller.startPanning);
    $('#paper').append(paperScroller.render().el);
    paperScroller.center();    //移动到页面的中间


    var commandManager = new joint.dia.CommandManager({
        graph: graph
    });


    paper.on('cell:pointerclick',function(cellView){
        //halo组件
        var halo = new joint.ui.Halo({ cellView: cellView});
        //link没有halo组件
        if (cellView.model instanceof joint.shapes.app.Link) return;
        //元素只连接元素
        halo.on('action:link:add', function(link) {
            if (!link.get('source').id || !link.get('target').id) {
                link.remove();
            }
        });
        halo.removeHandles();
        halo.render();
        //  console.log( JSON.stringify(graph.toJSON()));

        //halo组建中的删除
        halo.addHandle({ name: 'remove', position: 'nw', icon: 'img/shanchu.svg' });

        if(cellView.model.attributes.type === "basic.Text"){  //如果是展开表数据
            halo.addHandle({ name: 'myaction', position: 'ne', icon: 'img/zhankai.svg' });

            halo.changeHandle('myaction', {
                attrs: {
                    '.handle': {
                        'data-tooltip-class-name': 'small',
                        'data-tooltip': '关联表',
                        'data-tooltip-position': 'left'
                    }
                }
            });
            halo.on('action:myaction:pointerdown', function(evt) {
                evt.stopPropagation();
                console.log('zhankai')
            });
        }else {                                                 //如果是切换表
            halo.addHandle({ name: 'changeTable', position: 'ne', icon: 'img/changeTable.svg' });

            halo.changeHandle('changeTable', {
                attrs: {
                    '.handle': {
                        'data-tooltip-class-name': 'small',
                        'data-tooltip': '表过滤',
                        'data-tooltip-position': 'left'
                    }
                }
            });
            halo.on('action:changeTable:pointerdown', function(evt) {
                evt.stopPropagation();
                console.log('changeTable')
            });
        }

        //删除图标的tooltip
        halo.changeHandle('remove', {
            attrs: {
                '.handle': {
                    'data-tooltip-class-name': 'small',
                    'data-tooltip': '删除',
                    'data-tooltip-position': 'right'
                }
            }
        });
        //删除图标事件
        halo.on('action:remove:pointerdown', function(evt) {
            evt.stopPropagation();
            getOutboundElement(cellView.model,{outbound:true});
            cellView.model.remove();
        });


    });

    //元素间的对齐线
    var snaplines = new joint.ui.Snaplines({ paper: paper });
    snaplines.startListening();

    //鹰眼开始
    var nav = new joint.ui.Navigator({
        paperScroller: paperScroller,
        width: 133,
        height: 100,
        padding: 5,
        model: graph,
        gridSize: 1,
    });
    nav.$el.appendTo('#myholder-small');
    nav.render();

    //tooltip模块
    new joint.ui.Tooltip({
        target: '[data-tooltip]',
        rootTarget: document.body,
        direction: 'auto',
        padding: 15,
    });
    //构造实例
    var obj = new joint.shapes.basic.Text({
        position : {x:500,y:500},
        size : {"width":14*8.5,"height":16},
        attrs: {text: {"text":'这是一个表数据',"font-size":16,"fill":'#555'}}
    });
    var obj2 = new joint.shapes.basic.Text({
        position: {x : 600,y:500},
        size : {width: 16*8.5,height:16},
        attrs : {text : {"text":'D2W_DI_INPUTSTEP',"font-size":14,"fill":'#555'}}
    });
    var obj3 = new joint.shapes.basic.Text({
        position: {x : 600,y:500},
        size : {width: 16*8.5,height:16},
        attrs : {text : {"text":'D2W_DI_INPUTSTEP',"font-size":14,"fill":'#555'}}
    });
    var obj4 = new joint.shapes.bpmn.Choreography({
        "type": "bpmn.Choreography",
        "participants": [
            '数据对象表'
        ],
        "initiatingParticipant": "Potential Buyer",
        "position": {
            "x": 600,
            "y": 600
        },
        'size' : {
            'width':200,
            'height':100
        },
        "angle": 0,
        "embeds": "",
        "z": 1,
        "id":"1314",
        "subProcess": false,
        "content":"<table><tr><td class='fieldsTd'>数据对象id:</td><td>001122</td></tr><tr><td class='fieldsTd'>表名:</td><td>table</td></tr><tr><td class='fieldsTd'>对象中文名:</td><td>中文名</td></tr></table>",
        "attrs": {
            ".participant-rect": {
                "fill": "ff8040"
            },
            '.participant-label':{
                'fill': '#fff'
            },
            ".sub-process": {
                "visibility": "hidden",
                "data-sub-process": ""
            },
            'div': {
                "style":{"width":200,"height":100},
                //    'html': "<p>数据对象id : 001122</p><p>表名:table</p><p>对象中文名:中文名</p>"
            },
            '.body' : {

            },
        }
    });
    var obj5 = new joint.shapes.bpmn.Choreography({
        "type": "bpmn.Choreography",
        "participants": [
            '数据对象表2'
        ],
        "initiatingParticipant": "Potential Buyer",
        "position": {
            "x": 800,
            "y": 800
        },
        'size' : {
            'width':200,
            'height':100
        },
        "angle": 0,
        "embeds": "",
        "z": 1,
        "id":"520",
        "subProcess": false,
        "content":"<table><tr><td class='fieldsTd'>数据对象id:</td><td>001122</td></tr><tr><td class='fieldsTd'>表名:</td><td>table</td></tr><tr><td class='fieldsTd'>对象中文名:</td><td>中文名</td></tr></table>",
        "attrs": {
            ".participant-rect": {
                "fill": "ff8040"
            },
            '.participant-label':{
                'fill': '#fff'
            },
            ".sub-process": {
                "visibility": "hidden",
                "data-sub-process": ""
            },
            'div': {
                "style":{"width":200,"height":100},
                //    'html': "<p>数据对象id : 001122</p><p>表名:table</p><p>对象中文名:中文名</p>"
            },
            '.body' : {

            },
        }
    });

    var link1 = new joint.shapes.app.Link({
        "source":{"id":"1314"},
        "target":{"id":"520"},
        smooth: true,
        "id":"66666",
        "attrs":{
            ".connection":{"stroke":"#20C1DD","stroke-width":2,"pointerEvents":"none"},
            ".marker-target":{"fill":"#20C1DD","stroke":"#20C1DD","d":"M 10 0 L 0 5 L 10 10 z"},
        }
        ,
        "labels": [
            {"position": 0.5, "attrs": {"text": {"text": "link1"}}}
        ],
        '.tool-remove' : null
    });

    var link2 = new joint.shapes.app.Link({
        "source":{"id":"1314"},
        "target":{"id":"520"},
        //  "router":{"name":"manhattan"},
        //  "connector":{"name":"rounded"},
        smooth: true,
        "id":"55555",
        "attrs":{
            ".connection":{"stroke":"red","stroke-width":2,"pointerEvents":"none"},
            ".marker-target":{"fill":"red","stroke":"red","d":"M 10 0 L 0 5 L 10 10 z"},
        }
        ,
        "labels": [
            {"position": 0.5, "attrs": {"text": {"text": "link2"}}}
        ],
        '.tool-remove' : null
    });


   // link1.router('manhattan');
    link1.connector('smooth', { radius: 20 });

    link2.router('manhattan');
    link2.connector('rounded', { radius: 20 });
    console.log(link1);
    graph.addCells(obj,obj2,obj3,obj4,obj5,link1,link2);



/*        graph.fromJSON({"cells":[{"type":"basic.Text","position":{"x":771,"y":464},"size":{"width":126,"height":16},"angle":0,"id":"7be850a5-0b3a-45a4-b657-d25a34caf854","z":1,"attrs":{"text":{"font-size":16,"fill":"#555","text":"这是一个表数据"}}},{"type":"basic.Text","position":{"x":762,"y":570},"size":{"width":144,"height":16},"angle":0,"id":"541e279b-a57f-4556-a3a9-f71186e62755","z":2,"attrs":{"text":{"font-size":14,"fill":"#555","text":"D2W_DI_INPUTSTEP"}}},{"type":"basic.Text","position":{"x":762,"y":375},"size":{"width":144,"height":16},"angle":0,"id":"a8997a9f-3389-482c-96c4-6ea498a6b76e","z":3,"attrs":{"text":{"font-size":14,"fill":"#555","text":"D2W_DI_INPUTSTEP"}}},{"type":"basic.Circle","size":{"width":20,"height":20},"position":{"x":596,"y":444},"angle":0,"id":"7e711fe8-6342-445b-88db-9cdd4450b8d8","z":4,"attrs":{"circle":{"fill":"#4c87b9","stroke":"#4c87b9"},"text":{"text":"表转换","ref-y":30,"fill":"#000"}}},{"type":"basic.Text","position":{"x":300,"y":464},"size":{"width":144,"height":16},"angle":0,"id":"4cda468b-8a92-40e0-ae2e-217f06c05197","z":5,"attrs":{"text":{"font-size":14,"fill":"#555","text":"D2W_DI_INPUTSTEP"}}},{"type":"app.Link","smooth":true,"labels":[],"source":{"id":"4cda468b-8a92-40e0-ae2e-217f06c05197"},"target":{"id":"7e711fe8-6342-445b-88db-9cdd4450b8d8"},"id":"0eebf2c3-d8e3-49df-97fe-1812099ebe71","z":6,"attrs":{".connection":{"stroke":"#20C1DD","stroke-width":2,"pointerEvents":"none"},".marker-target":{"fill":"#20C1DD","stroke":"#fff","d":"M 10 0 L 0 5 L 10 10 z"}}},{"type":"app.Link","smooth":true,"labels":[],"source":{"id":"7e711fe8-6342-445b-88db-9cdd4450b8d8"},"target":{"id":"a8997a9f-3389-482c-96c4-6ea498a6b76e"},"id":"d3c92cb7-804b-421c-89d1-a4d37ad7a515","z":7,"attrs":{".connection":{"stroke":"#20C1DD","stroke-width":2,"pointerEvents":"none"},".marker-target":{"fill":"#20C1DD","stroke":"#fff","d":"M 10 0 L 0 5 L 10 10 z"}}},{"type":"app.Link","smooth":true,"labels":[],"source":{"id":"7e711fe8-6342-445b-88db-9cdd4450b8d8"},"target":{"id":"7be850a5-0b3a-45a4-b657-d25a34caf854"},"id":"dae1833e-746e-40ae-8cb4-fef35320d09b","z":8,"attrs":{".connection":{"stroke":"#20C1DD","stroke-width":2,"pointerEvents":"none"},".marker-target":{"fill":"#20C1DD","stroke":"#fff","d":"M 10 0 L 0 5 L 10 10 z"}}},{"type":"app.Link","smooth":true,"labels":[],"source":{"id":"7e711fe8-6342-445b-88db-9cdd4450b8d8"},"target":{"id":"541e279b-a57f-4556-a3a9-f71186e62755"},"id":"20d839b8-7dac-452d-9470-d4dc2b4e50d5","z":9,"attrs":{".connection":{"stroke":"#20C1DD","stroke-width":2,"pointerEvents":"none"},".marker-target":{"fill":"#20C1DD","stroke":"#fff","d":"M 10 0 L 0 5 L 10 10 z"}}},{"type":"basic.Circle","size":{"width":20,"height":20},"position":{"x":977,"y":260},"angle":0,"id":"8cdab337-e33f-421b-8b34-472129889f55","z":10,"attrs":{"circle":{"fill":"#4c87b9","stroke":"#4c87b9"},"text":{"text":"表转换","ref-y":30,"fill":"#000"}}},{"type":"basic.Text","position":{"x":1088,"y":615},"size":{"width":144,"height":16},"angle":0,"id":"ae1c6538-822f-4275-8000-d9c64df6c98c","z":11,"attrs":{"text":{"font-size":14,"fill":"#555","text":"D2W_DI_INPUTSTEP"}}},{"type":"basic.Text","position":{"x":1101,"y":175},"size":{"width":144,"height":16},"angle":0,"id":"1515b4f9-e8f0-469a-a500-08cfd5af7df2","z":12,"attrs":{"text":{"font-size":14,"fill":"#555","text":"D2W_DI_INPUTSTEP"}}},{"type":"basic.Text","position":{"x":1101,"y":344},"size":{"width":144,"height":16},"angle":0,"id":"ed237118-07b3-4ef4-b5be-63509b16118e","z":13,"attrs":{"text":{"font-size":14,"fill":"#555","text":"D2W_DI_INPUTSTEP"}}},{"type":"basic.Text","position":{"x":1101,"y":244},"size":{"width":144,"height":16},"angle":0,"id":"65bb0c74-360e-433f-9660-366b923d8c90","z":14,"attrs":{"text":{"font-size":14,"fill":"#555","text":"D2W_DI_INPUTSTEP"}}},{"type":"basic.Circle","size":{"width":20,"height":20},"position":{"x":957,"y":657},"angle":0,"id":"43bf3649-dad5-4966-a43b-6d85cbc268e0","z":15,"attrs":{"circle":{"fill":"#4c87b9","stroke":"#4c87b9"},"text":{"text":"表转换","ref-y":30,"fill":"#000"}}},{"type":"basic.Text","position":{"x":1088,"y":742},"size":{"width":144,"height":16},"angle":0,"id":"52521ec1-9431-4a33-a2d7-28c61709dfc4","z":16,"attrs":{"text":{"font-size":14,"fill":"#555","text":"D2W_DI_INPUTSTEP"}}},{"type":"basic.Text","position":{"x":1089,"y":677},"size":{"width":144,"height":16},"angle":0,"id":"e90251ef-ca68-4423-96fe-6f49a9dee5a6","z":17,"attrs":{"text":{"font-size":14,"fill":"#555","text":"D2W_DI_INPUTSTEP"}}},{"type":"app.Link","smooth":true,"labels":[],"source":{"id":"43bf3649-dad5-4966-a43b-6d85cbc268e0"},"target":{"id":"ae1c6538-822f-4275-8000-d9c64df6c98c"},"id":"6e44b37e-d0a3-4b1b-9e90-3dbf41c6978d","z":18,"attrs":{".connection":{"stroke":"#20C1DD","stroke-width":2,"pointerEvents":"none"},".marker-target":{"fill":"#20C1DD","stroke":"#fff","d":"M 10 0 L 0 5 L 10 10 z"}}},{"type":"app.Link","smooth":true,"labels":[],"source":{"id":"43bf3649-dad5-4966-a43b-6d85cbc268e0"},"target":{"id":"e90251ef-ca68-4423-96fe-6f49a9dee5a6"},"id":"b94ac0ef-ff8b-48b2-9bbd-38271a3f49b5","z":19,"attrs":{".connection":{"stroke":"#20C1DD","stroke-width":2,"pointerEvents":"none"},".marker-target":{"fill":"#20C1DD","stroke":"#fff","d":"M 10 0 L 0 5 L 10 10 z"}}},{"type":"app.Link","smooth":true,"labels":[],"source":{"id":"43bf3649-dad5-4966-a43b-6d85cbc268e0"},"target":{"id":"52521ec1-9431-4a33-a2d7-28c61709dfc4"},"id":"0167b294-7bad-4e88-8b9f-aa9acc3f1176","z":20,"attrs":{".connection":{"stroke":"#20C1DD","stroke-width":2,"pointerEvents":"none"},".marker-target":{"fill":"#20C1DD","stroke":"#fff","d":"M 10 0 L 0 5 L 10 10 z"}}},{"type":"app.Link","smooth":true,"labels":[],"source":{"id":"541e279b-a57f-4556-a3a9-f71186e62755"},"target":{"id":"43bf3649-dad5-4966-a43b-6d85cbc268e0"},"id":"8f6bd960-dc98-49b9-9a75-15e754dbb88e","z":21,"attrs":{".connection":{"stroke":"#20C1DD","stroke-width":2,"pointerEvents":"none"},".marker-target":{"fill":"#20C1DD","stroke":"#fff","d":"M 10 0 L 0 5 L 10 10 z"}}},{"type":"app.Link","smooth":true,"labels":[],"source":{"id":"a8997a9f-3389-482c-96c4-6ea498a6b76e"},"target":{"id":"8cdab337-e33f-421b-8b34-472129889f55"},"id":"84c50233-9ba6-44d0-b528-207d1084f0b2","z":22,"attrs":{".connection":{"stroke":"#20C1DD","stroke-width":2,"pointerEvents":"none"},".marker-target":{"fill":"#20C1DD","stroke":"#fff","d":"M 10 0 L 0 5 L 10 10 z"}}},{"type":"app.Link","smooth":true,"labels":[],"source":{"id":"8cdab337-e33f-421b-8b34-472129889f55"},"target":{"id":"ed237118-07b3-4ef4-b5be-63509b16118e"},"id":"3cb36de9-aebb-45ce-9a34-9137c396b619","z":23,"attrs":{".connection":{"stroke":"#20C1DD","stroke-width":2,"pointerEvents":"none"},".marker-target":{"fill":"#20C1DD","stroke":"#fff","d":"M 10 0 L 0 5 L 10 10 z"}}},{"type":"app.Link","smooth":true,"labels":[],"source":{"id":"8cdab337-e33f-421b-8b34-472129889f55"},"target":{"id":"65bb0c74-360e-433f-9660-366b923d8c90"},"id":"dcffcb13-7bbb-4315-b2a9-b02a64e77d6a","z":24,"attrs":{".connection":{"stroke":"#20C1DD","stroke-width":2,"pointerEvents":"none"},".marker-target":{"fill":"#20C1DD","stroke":"#fff","d":"M 10 0 L 0 5 L 10 10 z"}}},{"type":"app.Link","smooth":true,"labels":[],"source":{"id":"8cdab337-e33f-421b-8b34-472129889f55"},"target":{"id":"1515b4f9-e8f0-469a-a500-08cfd5af7df2"},"id":"2cdfaccb-5555-4a6c-bcab-de37fea73e6b","z":25,"attrs":{".connection":{"stroke":"#20C1DD","stroke-width":2,"pointerEvents":"none"},".marker-target":{"fill":"#20C1DD","stroke":"#fff","d":"M 10 0 L 0 5 L 10 10 z"}}}]})*/

    //得到字符串的长度
    function getStringLen(str){
        return str.replace(/[\u0391-\uFFE5]/g,"aa").length;
    }

    //得到所有出站的元素
    function getOutboundElement(elem,direction) {

        var list = [], //元素id数组
            eleList=[]; //元素数组
        list.push(elem.id); //排除当前元素id

        return (function findRelateModel(){     //子元素相关的所有元素
            var NeighborsBPMNArr = graph.getNeighbors(elem,direction);  //相邻元素数组
            $.each(NeighborsBPMNArr,function(i,v){        //遍历相关元素
                if(list.indexOf(v.id) === -1){
                    list.push(v.id);
                    eleList.push(v);
                    elem = v;                //当前元素
                    findRelateModel();       //回调 那不是
                }
            });
            //业务逻辑
            $.each(eleList,function (i, v) { //删除其他所有的元素
                v.remove();
            });
        })()
    }
})();



